import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd())
  
  return {
    plugins: [vue()],
    base: '/',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    server: {
      port: parseInt(env.VITE_DEV_SERVER_PORT || '3000'),
      open: env.VITE_DEV_SERVER_OPEN === 'true',
      cors: true,
      headers: {
        'Cross-Origin-Opener-Policy': 'same-origin',   // 保护你的源站点免受攻击你的源站点免受攻击
        'Cross-Origin-Embedder-Policy': 'require-corp'  // 保护你的源站点免受攻击你的源站点免受攻击
      },
      proxy: {
        '/api': {
          target: env.VITE_API_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          configure: (proxy, options) => {
            // 代理配置
            proxy.on('error', (err, req, res) => {
              console.log('proxy error', err)
            })
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log('Sending Request to the Target:', req.method, req.url)
            })
            proxy.on('proxyRes', (proxyRes, req, res) => {
              console.log('Received Response from the Target:', proxyRes.statusCode, req.url)
            })
          }
        }
      }
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: env.VITE_BUILD_SOURCEMAP === 'true',
      // 生产环境移除 console
      minify: mode === 'development' ? false : 'terser',
      terserOptions: {
        compress: {
          drop_console: env.VITE_BUILD_DROP_CONSOLE === 'true',
          drop_debugger: env.VITE_BUILD_DROP_DEBUGGER === 'true',
          // 避免过度优化导致的初始化问题
          unsafe_arrows: false,
          unsafe_comps: false,
          unsafe_Function: false,
          unsafe_math: false,
          unsafe_symbols: false,
          unsafe_proto: false,
          unsafe_regexp: false,
          unsafe_undefined: false
        },
        mangle: {
          // 保持函数名，避免初始化顺序问题
          keep_fnames: true
        }
      },
      // 静态资源处理
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]',
          // 优化分包策略以避免循环依赖
          manualChunks: (id) => {
            // Element Plus 相关
            if (id.includes('element-plus')) {
              return 'element-plus'
            }
            // Vue 核心
            if (id.includes('vue') && !id.includes('node_modules')) {
              return 'vue-core'
            }
            // Vue 生态
            if (id.includes('vue-router') || id.includes('vuex')) {
              return 'vue-ecosystem'
            }
            // 工具库
            if (id.includes('lodash') || id.includes('axios') || id.includes('dayjs')) {
              return 'utils'
            }
            // node_modules 中的 Vue
            if (id.includes('node_modules') && id.includes('vue')) {
              return 'vendor-vue'
            }
            // 其他第三方库
            if (id.includes('node_modules')) {
              return 'vendor'
            }
          }
        },
        // 防止循环依赖
        external: (id) => {
          // 对于特定的模块，不进行外部化
          return false
        }
      },
      // 构建优化
      chunkSizeWarningLimit: parseInt(env.VITE_BUILD_CHUNK_SIZE_WARNING_LIMIT || '2000'),
      // 启用 gzip 压缩
      reportCompressedSize: true,
      // 启用 CSS 代码分割
      cssCodeSplit: true,
      // 启用预加载
      assetsInlineLimit: 4096,
      // 目标浏览器
      target: 'es2015'
    },
    // 优化选项
    optimizeDeps: {
      include: [
        'vue', 
        'vue-router', 
        'vuex',  // 使用 vuex 而不是 pinia
        'element-plus', 
        'element-plus/es', 
        'element-plus/es/components/message/style/index',
        'element-plus/es/components/notification/style/index',
        'lodash', 
        'axios', 
        'dayjs'
      ],
      exclude: ['@ffmpeg/ffmpeg', '@ffmpeg/util']
    },
    // CSS 相关配置
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/variables" as *;`
        }
      }
    }
  }
}) 